package com.sun;

import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashSet;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j(topic = "c.ThreadPool01")
public class ThreadPool01 {
    public static void main(String[] args) {
        TreadPool treadPool = new TreadPool(2, 1000, TimeUnit.MILLISECONDS, 10);
        for (int i = 0; i < 5; i++) {
            int j = i;
            treadPool.execute(()->{
                log.info("{}",j);
            });
        }
    }
}
@Slf4j(topic = "c.TreadPool")
class TreadPool {
    //任务队列
    private BlockingQueue<Runnable> taskQueue;

    //线程集合
    private HashSet<Worker> workers = new HashSet();

    //核心线程数量
    private int coreSize;

    //获取任务的超时时间
    private long timeout;

    //
    private TimeUnit timeUnit;

    public TreadPool(int coreSize, long timeout, TimeUnit timeUnit, int queueCapity) {
        this.coreSize = coreSize;
        this.timeout = timeout;
        this.timeUnit = timeUnit;
        this.taskQueue = new BlockingQueue<>(queueCapity);
    }

    //执行任务
    public void execute(Runnable task) {
        //当任务数没有超过coreSize，直接交给work对象执行
        //如果任务数超过了coreSize，我们就需要将其加入任务队列暂存
        synchronized (workers) {
            if (workers.size() < coreSize) {
                Worker worker = new Worker(task);
                log.info("新增worker{},{}",worker,task);
                workers.add(worker);
                worker.start();
            } else {
                log.info("加入任务队列{}",task);
                taskQueue.put(task);
            }
        }
    }

    class Worker extends Thread {

        private Runnable task;

        public Worker(Runnable task) {
            this.task = task;
        }

        @Override
        public void run() {
            //执行任务
            //1 当task不为null执行任务

            //2 当task执行完毕，再接着从任务队列获取任务
            while (task != null || (task = taskQueue.poll(timeout,timeUnit)) != null) {
                try {
                    log.info("正在执行...{}",task);
                    task.run();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    task = null;
                }
            }

            synchronized (workers) {
                log.info("workers被移除{}",this);
                workers.remove(this);
            }

        }
    }
}

class BlockingQueue<T> {
    //任务队列
    private Deque<T> queue = new ArrayDeque<>();

    //锁
    private Lock lock = new ReentrantLock();

    //生产者条件变量
    private Condition fullWaitSet = lock.newCondition();

    //消费者条件变量
    private Condition emptyWaitSet = lock.newCondition();

    //容量
    private int capcity;

    public BlockingQueue(int queueCapity) {
        this.capcity = queueCapity;
    }

    //带超时的阻塞获取
    public T poll(long timeout, TimeUnit unit) {
        try {
            lock.lock();
            //将超时时间统一转换为纳秒
            long nanos = unit.toNanos(timeout);
            while (queue.isEmpty()) {
                //剩余时间
                if (nanos <= 0) {
                    return null;
                }
                nanos = emptyWaitSet.awaitNanos(nanos);
            }
            T t = queue.removeFirst();
            fullWaitSet.signal();
            return t;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return null;
    }

    //阻塞获取
    public T take() {

        try {
            lock.lock();
            while (queue.isEmpty()) {
                emptyWaitSet.await();
            }
            T t = queue.removeFirst();
            fullWaitSet.signal();
            return t;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return null;
    }

    //阻塞添加
    public void put(T element) {
        try {
            lock.lock();
            while (queue.size() == capcity) {
                fullWaitSet.await();
            }
            queue.addLast(element);
            emptyWaitSet.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    //获取队列大小
    public int size() {
        try {
            lock.lock();
            return queue.size();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return 0;
    }

    public static void main(String[] args) {
        JSONObject obj = new JSONObject();
        obj.set("zhangsan","zs");
        System.out.println(obj);
        System.out.println(obj.toJSONString(0));
    }
}
